<template>
  <div class="autManage-wrapper">
    <!-- 左侧 角色树 -->
    <div class="left-wrapper content-wrapper">
      <span class="title">角色选择</span>
      <role-tree
          :type="1"
          ref="roleTree"
          :dropMenuShow="dropMenuVisible"
          :dropMenuList="autDropMenu"
          :propsParam="treeParam"
          @getNodeInfo="getRolesInfo"
          @menuOperations="autMenuOperations"
      ></role-tree>
    </div>
    <!-- 中间 table 列表 -->
    <div class="center-wrapper content-wrapper">
      <div class="center-title">
        <span class="title">{{ title }}</span>
        <div class="systemTabs">
          <span :class="[tabActive?'active':'',isSuperAdmin?'':'notSuperAdmin']" @click="toUserTab">分派人员</span>
          <span :class="tabActive?'':'active'" @click="toRoleTab" v-if="isSuperAdmin">角色分配</span>
        </div>
      </div>
      <div class="user-table" v-if="tabActive">
        <!-- 分派人员 -->
        <div class="userTable-buttons">
          <div class="userType">
            <span :class="userActive? 'active':''" @click="changeUserType(1)">当前用户</span>
            <span :class="userActive? '':'active'" @click="changeUserType(0)">所有用户</span>
          </div>
          <el-input placeholder="请输入用户名" v-model="searchValue" class="systemInput" @change="searchUser">
            <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
          </el-input>
          <span class="systemButtonCancel" @click="addOrdelete">{{ userOperation }}</span>
        </div>
        <el-table
            :data="userTableData"
            class="systemTable"
            stripe
            style="width: 100%"
            height="calc(100% - 57px)"
            tooltip-effect="dark"
            @selection-change="handleSelectionChange"
        >
          <el-table-column
              type="selection"
              label-class-name="disabledSelection"
              width="80"
              header-align="center"
              align="center"
          ></el-table-column>
          <el-table-column prop="name" label="姓名" width="180" show-overflow-tooltip></el-table-column>
          <el-table-column prop="account" label="账号" width="180" show-overflow-tooltip></el-table-column>
          <el-table-column prop="code" label="工号" show-overflow-tooltip></el-table-column>
          <el-table-column prop="deptName" label="部门" show-overflow-tooltip></el-table-column>
          <el-table-column prop="phone" label="手机" show-overflow-tooltip></el-table-column>
          <el-table-column prop="telephone" label="电话" show-overflow-tooltip></el-table-column>
        </el-table>
      </div>

      <!-- 分派角色 -->
      <div class="role-table" v-if="!tabActive">
        <div class="roleTable-buttons">
          <span class="systemButtonCancel" @click="addRoles">添加所属角色</span>
          <span class="systemButtonCancel" @click="addOrdelete">移除</span>
        </div>
        <el-table
            class="systemTable"
            :data="roleTableData"
            stripe
            style="width: 100%;"
            height="calc(100% - 108px);"
            tooltip-effect="dark"
            @selection-change="handleSelectionChange"
        >
          <el-table-column
              type="selection"
              label-class-name="disabledSelection"
              width="80"
              header-align="center"
              align="center"
          ></el-table-column>
          <el-table-column prop="ADMINROLENAME" label="管理员名称" show-overflow-tooltip></el-table-column>
          <el-table-column prop="ROLENAME" label="角色名称" show-overflow-tooltip></el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 右侧 菜单树 -->
    <div class="right-wrapper content-wrapper">
      <div class="left-menuTree">
        <span class="title">菜单选择</span>
        <menu-tree ref="menuTree" :type="0" @getNodeInfo="getMenuInfo" :param="param"></menu-tree>
      </div>
      <div class="right-roles">
        <el-checkbox
            class="systemCheckbox"
            @change="menuTreeRoleChange"
            v-for="item in menuAutList"
            :label="item"
            :key="item.id"
            :checked="item.check"
            :disabled="!Boolean(currentRole.isOper)"
        >{{ item.name }}
        </el-checkbox>
      </div>
    </div>
    <role-tree
        v-if="selectNewRoleShow"
        :type="1"
        :dialogShow="1"
        :propsParam="roleTreeParam"
        dialogTitle="添加所属角色"
        @getCheckedRoles="selectNewRole"
        @treeCancel="selectNewRoleShow=false"
    ></role-tree>
    <div class="maskCenter" v-if="dialogFormVisible">
      <div class="systemDialog" style="width: 473px;height: 329px;">
        <div class="dialog-header" v-winmove>
          <span>{{ dialogFormTitle }}</span>
        </div>
        <div class="dialog-body">
          <el-form :model="dialogForm" class="systemForm">
            <el-form-item label="名称:" label-width="50px">
              <el-input class="systemInput" v-model="dialogForm.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="编码:" label-width="50px">
              <el-input class="systemInput" v-model="dialogForm.code" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div class="dialog-footer right">
          <span class="systemButtonConfirm" @click="dialogFormSave">保存</span>
          <span class="systemButtonCancel" @click="dialogFormCancel">取消</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import RoleTree from '@/system/components/organizationTree'
import MenuTree from '@/system/components/menuTree'

import {userList} from '@/system/api/organization/organization'
import {
  deleteRoleUsers,
  saveRoleUsers,
  roleAdminlist,
  deleteRoleAdmins,
  saveRoleAdmins,
  menuAutSave,
  menuAutDelete,
  roleSave,
  roleDetail,
  roleDelete,
} from '@/system/api/organization/roleManage'
import {autList} from '@/system/api/menuManage'
import winmove from '@/directives/winmove'

export default {
  data() {
    return {
      treeParam: {
        parentId: 0,
        type: 1,
      },
      title: '分派人员',
      tabActive: true, // 分派人员
      userActive: true, // 当前用户
      currentRole: {},
      userOperation: '移除人员',
      userTableData: [],
      selectedUsers: [],
      roleTableData: [],
      selectedRoles: '',
      searchValue: '',
      selectNewRoleShow: false,
      checkRolesList: [],
      menuAutList: [],
      currentMenu: {},
      autDropMenu: [],
      currentRoleNode: [],
      currentRoleNodeInfo: [],
      autMenuOperationType: '',
      dialogFormVisible: false,
      dialogForm: {},
      dialogFormTitle: '',
      isSuperAdmin: this.$store.state.user.info.flag,
      dropMenuVisible: 1,
      param: {
        parentId: 0,
        state: 1,
      },
      roleTreeParam: {
        checkBoxShow: 1
      }
    }
  },
  components: {
    RoleTree,
    MenuTree,
  },
  directives: {
    winmove,
  },
  methods: {
    // 角色树 点击
    async getRolesInfo(e) {
      if (e.clickType) {
        this.searchValue = ''
        this.menuAutList = []
        this.currentRole = {}
        this.$refs.menuTree.highLightNode()
        this.userTableData = []
        this.roleTableData = []
        if (e.type) {
          this.currentRole = JSON.parse(JSON.stringify(e))
          this.userActive = true
          this.refreshUserList(e.id)
        }
      } else {
        const isOper = e.data.isOper
        const type = e.data.type
        this.dropMenuVisible = 1
        if (isOper) {
          this.autDropMenu = type
              ? [
                {
                  index: 2,
                  label: '编辑',
                  icon: 'icon iconfont iconbiaoge-bianji',
                },
                {
                  index: 3,
                  label: '删除',
                  icon: 'icon iconfont iconbiaoge-shanchu',
                },
              ]
              : [
                {
                  index: 0,
                  label: '新增角色',
                  icon: 'icon iconfont iconzengjia',
                },
                {
                  index: 1,
                  label: '新增路径',
                  icon: 'icon iconfont iconzengjia',
                },
                {
                  index: 2,
                  label: '编辑',
                  icon: 'icon iconfont iconbiaoge-bianji',
                },
                {
                  index: 3,
                  label: '删除',
                  icon: 'icon iconfont iconbiaoge-shanchu',
                },
              ]
        } else {
          if (e.data.id === 1) {
            this.autDropMenu = [
              {
                index: 0,
                label: '新增角色',
                icon: 'icon iconfont iconzengjia',
              },
            ]
          } else {
            this.dropMenuVisible = 0
          }
        }
        this.currentRoleNode = e
        let nodeDetail = await roleDetail({id: e.data.id})
        this.currentRoleNodeInfo = nodeDetail.info
      }
    },
    // 人员&角色 tab 切换
    toUserTab() {
      this.tabActive = true
      if (this.currentRole.id || this.currentRole.id === 0) {
        this.refreshUserList(this.currentRole.id, this.searchValue)
      }
    },
    toRoleTab() {
      this.tabActive = false
      if (this.currentRole.id || this.currentRole.id === 0) {
        this.refreshUserList(this.currentRole.id)
      }
    },
    searchUser() {
      if (this.currentRole.id || this.currentRole.id === 0) {
        let id = this.userActive ? this.currentRole.id : null
        this.refreshUserList(id, this.searchValue)
      } else {
        this.message('请先选择角色', 3)
        return
      }
    },
    // table 刷新
    refreshUserList(id, value) {
      if (this.tabActive) {
        userList({roleId: id, name: value}).then((res) => {
          if (res.success) {
            this.userTableData = JSON.parse(
                JSON.stringify(res.info)
            )
          } else this.message(res.msg, 3)
        })
      } else {
        roleAdminlist({adminRole: id}).then((res) => {
          if (res.success) {
            this.roleTableData = JSON.parse(
                JSON.stringify(res.info)
            )
          } else this.message(res.msg, 3)
        })
      }
    },
    // table 勾选
    handleSelectionChange(e) {
      this.selectedUsers = JSON.parse(JSON.stringify(e))
    },
    // 添加&移除 人员&角色
    addOrdelete() {
      if (this.selectedUsers.length === 0) {
        let warningText = this.tabActive
            ? '请先选择人员'
            : '请先选择角色'
        this.message(warningText, 3)
      } else {
        let warningText = this.userActive ? '确认移除？' : '确认添加？'
        this.messageBox(warningText).then((c) => {
          if (c.action) {
            if (this.tabActive) {
              let operation = this.userActive
                  ? deleteRoleUsers
                  : saveRoleUsers
              let ids = this.selectedUsers[0].id
              for (
                  let i = 1;
                  i < this.selectedUsers.length;
                  i++
              ) {
                ids = ids + ',' + this.selectedUsers[i].id
              }
              operation({
                roleId: this.currentRole.id,
                userIds: ids,
              }).then((res) => {
                if (res.success) {
                  this.message(res.msg, 1)
                  this.changeUserType(1)
                } else this.message(res.msg, 3)
              })
            } else {
              let ids = this.selectedUsers[0].ROLEID
              for (
                  let i = 1;
                  i < this.selectedUsers.length;
                  i++
              ) {
                ids = ids + ',' + this.selectedUsers[i].ROLEID
              }
              deleteRoleAdmins({
                adminRole: this.currentRole.id,
                roleIds: ids,
              }).then((res) => {
                if (res.success) {
                  this.message(res.msg, 1)
                  this.refreshUserList(this.currentRole.id)
                } else this.message(res.msg, 3)
              })
            }
          }
        })
      }
    },
    // userTable 切换当前&所有人员
    changeUserType(type) {
      if (!this.currentRole.id) {
        this.message('请先选择角色', 3)
        return
      } else {
        this.selectedUsers = []
        this.searchValue = ''
        if (!type) {
          this.userActive = false
          this.refreshUserList()
          this.userOperation = '添加人员'
        } else {
          this.userActive = true
          this.refreshUserList(this.currentRole.id)
          this.userOperation = '移除人员'
        }
      }
    },
    addRoles() {
      if (!this.currentRole.id) {
        this.message('请先选择角色', 3)
        return
      } else {
        this.selectNewRoleShow = true
      }
    },
    selectNewRole(e) {
      if (e.length === 0) {
        this.message('请选择需要添加的角色', 3)
        return
      }
      let datas = JSON.parse(JSON.stringify(e))
      let ids = datas[0].id
      for (let i = 1; i < datas.length; i++) {
        ids = ids + ',' + datas[i].id
      }
      saveRoleAdmins({
        adminRole: this.currentRole.id,
        roleIds: ids,
      }).then((res) => {
        if (res.success) {
          this.roleTableData = res.info
          this.selectNewRoleShow = false
          this.refreshUserList(this.currentRole.id)
          this.message(res.msg, 1)
        } else this.message(res.msg, 3)
      })
    },
    getMenuInfo(e) {
      if (!this.currentRole.type) {
        this.message('请先选择角色', 3)
        this.$refs.menuTree.highLightNode()
        return
      } else {
        this.currentMenu = e
        autList({
          roleId: this.currentRole.id,
          funcId: e.id,
        }).then((res) => {
          if (res.success) {
            this.menuAutList = JSON.parse(JSON.stringify(res.info))
          }
        })
      }
    },
    menuTreeRoleChange(f, e) {
      let obj = JSON.parse(JSON.stringify(e.target))
      let aut = obj._value
      let params = {
        roleId: this.currentRole.id,
        autId: aut.id,
      }
      let URL = aut.check ? menuAutDelete : menuAutSave
      URL(params).then((res) => {
        if (res.success) {
          this.message(res.msg, 1)
          setTimeout(() => {
            this.getMenuInfo(this.currentMenu)
          }, 500)
        } else this.message(res.msg, 3)
      })
    },
    autMenuOperations(e) {
      this.autMenuOperationType = e
      if (!this.currentRoleNodeInfo.type) {
        this.dialogFormVisible = true
        switch (Number(e)) {
          case 0:
            this.dialogFormTitle = '新增角色'
            this.dialogForm = {
              parentId: this.currentRoleNodeInfo.id,
              type: 1,
            }
            this.currentRoleNode.operationType = 1
            break
          case 1:
            this.dialogFormTitle = '新增路径'
            this.dialogForm = {
              parentId: this.currentRoleNodeInfo.id,
              type: 0,
            }
            this.currentRoleNode.operationType = 1
            break
          case 2:
            this.dialogFormTitle = '编辑路径'
            this.dialogForm = this.currentRoleNodeInfo
            this.currentRoleNode.operationType = 0
            break
          default:
            this.dialogFormVisible = false
            this.messageBox('确认删除？').then((c) => {
              if (c.action) {
                roleDelete({
                  id: this.currentRoleNodeInfo.id,
                }).then((res) => {
                  if (res.success) {
                    this.message(res.msg, 1)
                    this.currentRoleNode.operationType = 0
                    this.$refs.roleTree.refreshNode(
                        this.currentRoleNode
                    )
                  } else this.message(res.msg, 3)
                })
              }
            })
        }
      } else {
        switch (Number(e)) {
          case 2:
            this.dialogFormVisible = true
            this.dialogFormTitle = '编辑角色'
            this.dialogForm = this.currentRoleNodeInfo
            this.currentRoleNode.operationType = 0
            break
          default:
            this.messageBox('确认删除？').then((c) => {
              if (c.action) {
                roleDelete({
                  id: this.currentRoleNodeInfo.id,
                }).then((res) => {
                  if (res.success) {
                    this.message(res.msg, 1)
                    this.currentRoleNode.operationType = 0
                    this.$refs.roleTree.refreshNode(
                        this.currentRoleNode
                    )
                  } else this.message(res.msg, 3)
                })
              }
            })
        }
      }
    },
    dialogFormCancel() {
      let warningText =
          this.autMenuOperationType === 2
              ? '确认取消编辑？'
              : '确认取消新增'
      this.messageBox(warningText).then((c) => {
        if (c.action) {
          this.dialogFormVisible = false
          this.dialogForm = {}
          this.dialogFormTitle = ''
        }
      })
    },
    dialogFormSave() {
      if (!this.dialogForm.name) {
        this.message('请输入名称', 3)
        return
      }
      roleSave(this.dialogForm).then((res) => {
        if (res.success) {
          this.$refs.roleTree.refreshNode(this.currentRoleNode)
          this.message(res.msg, 1)
          this.dialogFormVisible = false
        } else this.message(res.msg, 3)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.autManage-wrapper {
  min-width: 1164px;
  text-align: left;
  height: 100%;
  width: 100%;

  .left-wrapper > .title,
  .center-wrapper > .center-title > .title,
  .right-wrapper > .left-menuTree > .title {
    text-align: left;
    display: inline-block;
    padding-left: 12px;
    position: relative;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 23px;
    color: var(--organization-tabs-text-color);

    &::before {
      content: '';
      display: block;
      width: 4px;
      height: 20px;
      background: rgba(83, 167, 255, 1);
      border-radius: 2px;
      position: absolute;
      top: 0;
      left: 0;
    }
  }

  .left-wrapper {
    height: 100%;
    float: left;
    width: 260px;
    border-radius: 6px;
    padding: 16px 0;
    overflow: auto;

    .title {
      margin: 23px 16px;
      margin-top: 0;
      border-bottom: none;
      padding-bottom: 0;
    }
  }

  .center-wrapper {
    float: left;
    width: calc(100% - 632px);
    height: 100%;
    margin: 0 12px;
    border-radius: 6px;

    .center-title {
      position: relative;
      height: 52px;
      margin: 0 12px;
      border-bottom: 2px solid var(--organization-title-underline-color);

      .title {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        left: 0;
      }

      .systemTabs {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        right: 0;

        span.notSuperAdmin {
          border-radius: 4px;
        }
      }
    }

    .user-table {
      height: calc(100% - 51px);

      .userTable-buttons {
        height: 57px;
        line-height: 57px;
        width: 100%;
        padding: 0 20px;
        display: inline-flex;
        align-items: center;
        position: relative;

        .userType {
          display: inline-block;
          cursor: pointer;
          color: var(--organization-role-person-color);
          float: left;

          span {
            margin-right: 20px;

            &.active {
              font-weight: bold;
              color: var(--organization-role-person-chosen-color);
            }
          }
        }

        .systemInput {
          float: left;
          width: 230px;
          position: relative;

          ::v-deep.el-input-group__append {
            background-color: transparent;
            position: absolute;
            top: 50%;
            right: 0;
            transform: translateY(-50%);
            border: none;
          }
        }

        .systemButtonCancel {
          position: absolute;
          right: 20px;
        }
      }

      .el-table {
        ::v-deep.el-table__body-wrapper {
          overflow: auto;
        }
      }
    }

    .role-table {
      height: calc(100% - 51px);

      .roleTable-buttons {
        height: 56px;
        line-height: 56px;
        float: right;
        margin-right: 12px;

        span {
          margin-left: 20px;
        }
      }

      .el-table {
        ::v-deep.el-table__body-wrapper {
          overflow: auto;
        }
      }
    }
  }

  .right-wrapper {
    height: 100%;
    float: left;
    width: 346px;
    border-radius: 6px;
    padding: 16px 0;
    display: inline-flex;
    flex-direction: row;

    .left-menuTree {
      height: 100%;
      overflow: auto;
      width: calc(100% - 129px);

      .title {
        margin: 23px 16px;
        margin-top: 0;
        border-bottom: none;
        padding-bottom: 0;
      }
    }

    .right-roles {
      width: 129px;
      border-left: 1px solid var(--organization-title-underline-color);
      margin-left: 2px;
      height: 100%;
      padding: 12px;
      overflow: auto;
      display: flex;
      flex-direction: column;

      .el-checkbox {
        margin-bottom: 20px;
      }
    }
  }
}
</style>
